# -*- coding = utf-8 -*-
# @Time : 2023/3/13 2:46
# @Author : 龙王赘婿_彪少
# @File : mycom_thread.py
# @Software: PyCharm

# 目标：
# 1、发送任意报文给指定串口
# 2、接收并显示报文
# 3、灵活加校验
import serial
import time
import struct
import binascii
import threading


class COM:
    __doc__ = ["https://blog.csdn.net/u010835747/article/details/111407089"]
    __doc__ += ["https://blog.csdn.net/weixin_39541869/article/details/110967865"]

    port = "com30"
    baudrate = 115200
    ser = serial.Serial()
    Read_frequency = 20
    Read_period = 1 / Read_frequency

    def com_init(self):
        self.ser.port = self.port
        self.ser.baudrate = self.baudrate
        self.ser.bytesize = 8
        self.ser.stopbits = 1
        self.ser.parity = 'N'
        self.ser.open()
        self.ser.timeout = self.Read_period  # 阻塞函数的超时时间，单位s，read(),readline(),readall()
        if self.ser.isOpen():
            print('*' * 20 + f"  串口：{self.ser.port}，打开成功，波特率：{self.ser.baudrate}  " + '*' * 20)
            return True
        else:
            print('*' * 20 + "  串口打开失败  " + '*' * 20)
            return False

    # 传入bytes并打印显示
    def read_data_analysis(self, raw_data):
        # print(f"接收原始数据：{raw_data}")
        hex_data = binascii.b2a_hex(raw_data)
        print(f"接收:len = {len(hex_data)} data = {hex_data}")

    # 传入bytes,或只含hex的string并转换格式发送
    def send_bytes_to_com(self, send_data):
        hex_data = binascii.a2b_hex(send_data)
        # hex_data = bytes.fromhex(send_data)   # 等效
        self.ser.write(hex_data)
        # print(f"发送原始数据：{hex_data}")
        print(f"发送:len = {len(send_data)} data = {send_data}")

    # 传入string并转换gbk格式发送
    def send_string_to_com(self, send_data):
        hex_data = send_data.encode('gbk')
        # hex_data = send_data.encode('utf-8')
        self.ser.write(hex_data)
        # print(f"发送原始数据：{hex_data}")
        print(f"发送:len = {len(send_data)} data = {send_data}")

    def read_thread(self):
        print("read thread is start!")
        while True:
            raw_data = self.ser.readall()
            if len(raw_data) > 0:
                self.read_data_analysis(raw_data)

    def send_thread(self):
        print("send thread is start!")
        send_data = "liuhibiao"
        self.send_string_to_com(send_data)

    def __init__(self):
        if self.com_init():
            th_read = threading.Thread(target=self.read_thread)
            th_send = threading.Thread(target=self.send_thread)
            th_read.start()
            time.sleep(0.01)
            th_send.start()
            th_read.join()
            th_send.join()


if __name__ == "__main__":
    c = COM()
